package com.heima;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CalcArticleScoreTask {

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "*/5 * * * * ?")
    public void calcArticleScoreTask(){
        boolean locked = false;
        RLock lock = null;
        try{
            // 加分布式锁
            lock = redissonClient.getLock("demo-lock");
            locked = lock.tryLock(0, 20, TimeUnit.SECONDS);
            // 如果加锁成功
            if(locked){
                log.info("获取分布式锁成功");
                // 做任务的业务逻辑
                log.info("计算文章分值任务开始");
                Thread.sleep(4000);
            }else{
                log.info("获取分布式锁失败，结束");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            // 释放分布式锁
            if(locked){
                lock.unlock();
            }
        }
    }

}
